package com.utilviet.baovn;

import android.app.Activity;
import android.content.Context;
import android.app.Fragment;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Parcelable;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout.LayoutParams;

import com.utilviet.baovn.objects.CustomWebView;
import com.utilviet.baovn.objects.Global;
import com.utilviet.baovn.objects.ICustomWebView;
import com.utilviet.baovn.objects.OnSwipeTouchListener;

import java.util.ArrayList;


/**
 * A placeholder fragment containing a simple view.
 */
public class WebviewFragment extends Fragment {

    private WebViewPagerAdapter mWebViewPagerAdapter = new WebViewPagerAdapter();
    private ViewPager mWebViewPager = null;
    protected ArrayList<CustomWebView> mWebViews = new ArrayList<CustomWebView>();
    private boolean mIsShowShare = false;
    private boolean mIsOpenNewUrl = false;
    private boolean mIsUserTouch = false;
    public  IWebVIewFragment mIWebViewFragment = null;
    private ICustomWebView mICustomWebView = new ICustomWebView() {
        @Override
        public void customWebViewDidClickLink(CustomWebView webView, String url) {
            if (mIsUserTouch) {
                pushUrl(url, true);
            }
            //redirect url. Ex: m.baomoi.com, m.autopro.com.vn
            else {
                webView.loadUrl(url);
            }

        }

        @Override
        public void customWebViewWillShare(CustomWebView webView, String url) {
            invokeShare(url);
        }
    };

    public WebviewFragment() {
    }

    public void cleanAndOpenUrl(String url) {
        if (url == null) {
            return;
        }

        for (int i = 0 ; i < mWebViews.size() ; i++) {
            CustomWebView webView = mWebViews.get(i);
            webView.mWebView.stopLoading();
        }

        mWebViews.clear();

        pushUrl(url, false);
    }

    private void pushUrl(String url, boolean animated) {
        LayoutInflater inflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        CustomWebView webView = (CustomWebView)inflater.inflate(R.layout.custom_webview, null);
        webView.mICustomWebView = mICustomWebView;
        webView.loadUrl(url);

        mWebViews.add(webView);

        mIsOpenNewUrl = true;
        renderViewPager();
        mIsOpenNewUrl = false;

        mIsUserTouch = false;

        if (animated) {
            mWebViewPager.setCurrentItem(mWebViews.size() - 1, true);
        }
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setRetainInstance(true);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        // Fragment layout
        View view = inflater.inflate(R.layout.webview_fragment, container, false);

        mWebViewPager = (ViewPager) view.findViewById(R.id.webViewViewPager);
        mWebViewPager.setOffscreenPageLimit(3);
        mWebViewPager.setAdapter(mWebViewPagerAdapter);
        mWebViewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {

            @Override
            public void onPageSelected(int arg0) {

            }

            @Override
            public void onPageScrolled(int pageIndex, float arg1, int offsetX) {

                if (mWebViews.size() > 1 && mWebViews.size() - 2 == pageIndex && offsetX == 0 && mIsOpenNewUrl == false) {
                    mWebViews.remove(mWebViews.size() - 1);//remove last
                    renderViewPager();
                }
            }

            @Override
            public void onPageScrollStateChanged(int arg0) {
            }
        });

        mWebViewPager.setOnTouchListener(new OnSwipeTouchListener(getActivity()) {
            @Override
            public void onSwipeRight() {

                if (mIWebViewFragment != null && mWebViews.size() == 1) {
                    mIWebViewFragment.onSwipeRightShowMenu(WebviewFragment.this);
                }
            }
        });

        View coverView = view.findViewById(R.id.coverView);
        coverView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                mIsUserTouch = true;
                return false;
            }
        });

        return view;
    }

    public void invokeShare(String url) {
        if (url == null || mIsShowShare) {
            return;
        }

        mIsShowShare = true;

        Intent shareIntent = new Intent(android.content.Intent.ACTION_SEND);
        shareIntent.setType("text/plain");
        shareIntent.putExtra(android.content.Intent.EXTRA_TEXT, url);

        getActivity().startActivity(Intent.createChooser(shareIntent, "Share"));
    }

    @Override
    public void onResume() {
        super.onResume();

        mIsShowShare = false;
    }

    private void renderViewPager() {
        if (mWebViewPagerAdapter != null) {
            mWebViewPagerAdapter.notifyDataSetChanged();
        }
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
    }

    private class WebViewPagerAdapter extends PagerAdapter {
        private int selectedWebViewId = -1;

        @Override
        public int getCount() {
            return mWebViews.size();
        }

        /**
         * Create the page for the given position.  The adapter is responsible
         * for adding the view to the container given here, although it only
         * must ensure this is done by the time it returns from
         * {@link #finishUpdate(android.view.ViewGroup)}.
         *
         * @param collection The containing View in which the page will be shown.
         * @param position The page position to be instantiated.
         * @return Returns an Object representing the new page.  This does not
         * need to be a View, but can be some other container of the page.
         */
        @Override
        public Object instantiateItem(ViewGroup collection, int position) {
            View view = (View)mWebViews.get(position);

            view.setLayoutParams(new ViewGroup.LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.MATCH_PARENT));
            collection.addView(view);

            return view;

//			TextView textView = new TextView(getMainActivity());
//			textView.setText("Index " + position);
//			textView.setTextColor(Color.BLACK);
//			textView.setTextSize(20);
//			textView.setLayoutParams(new ViewGroup.LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.MATCH_PARENT));
//			collection.addView(textView);
//			return textView;
        }

        /**
         * Remove a page for the given position.  The adapter is responsible
         * for removing the view from its container, although it only must ensure
         * this is done by the time it returns from {@link #finishUpdate(android.view.ViewGroup)}.
         *
         * @param collection The containing View from which the page will be removed.
         * @param position The page position to be removed.
         * @param view The same object that was returned by
         * {@link #instantiateItem(android.view.View, int)}.
         */
        @Override
        public void destroyItem(ViewGroup collection, int position, Object view) {
            collection.removeView((View) view);
        }


        /**
         * Determines whether a page View is associated with a specific key object
         * as returned by instantiateItem(ViewGroup, int). This method is required
         * for a PagerAdapter to function properly.
         * @param view Page View to check for association with object
         * @param object Object to check for association with view
         * @return
         */
        @Override
        public boolean isViewFromObject(View view, Object object) {
            return (view==object);
        }

        /**
         * Called when the a change in the shown pages has been completed.  At this
         * point you must ensure that all of the pages have actually been added or
         * removed from the container as appropriate.
         * @param arg0 The containing View which is displaying this adapter's
         * page views.
         */
        @Override
        public void finishUpdate(ViewGroup arg0) {
        }

        @Override
        public void restoreState(Parcelable arg0, ClassLoader arg1) {
            Bundle bd = (Bundle) arg0;
            this.selectedWebViewId = bd.getInt(Global.SELECTED_WEBVIEW_ID);
        }

        @Override
        public Parcelable saveState() {
            Bundle bd = new Bundle();
            bd.putInt(Global.SELECTED_WEBVIEW_ID, this.selectedWebViewId);
            return bd;
        }

        public int getItemPosition(Object object) {
            return POSITION_NONE;
        }

        @Override
        public void startUpdate(ViewGroup arg0) {
        }
    }
}
